<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

/**
 * 首页接口
 */
class Guide extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     *
     * 
     */
    public function index()
    {
        $type = $this->request->post('type');
        $address = $this->request->post('address');
        // 店铺
        $merchant = Db::name('merchant')
            ->join('x_sort','x_sort.id = x_merchant.sort_id')
            ->join('x_floor','x_floor.id = x_merchant.floor_id')
            ->field('x_merchant.*,x_sort.name as sort,x_floor.name as floor')
            ->where(function ($query) use ($type,$address){
                if($type > 0){
                    $query->where('x_merchant.sort_id',$type);
                }
                if($address > 0){
                    $query->where('x_merchant.floor_id',$address);
                }
            })->select();
        // 业态
        $sort = Db::name('sort')->select();
        // 积分商品
        $floor = Db::name('floor')->select();
        return json_encode(array('merchant'=>$merchant,'sort'=>$sort,'floor'=>$floor));
    }
    public function detail(){
        $id = $this->request->post('id');
        $people = model('People')->people($this->request->post('openid'));
        // 是否收藏
        $star = Db::name('keep')->where(array('people_id'=>$people['id'],'merchant_id'=>$id))->find();
        // 店铺信息
        $res = Db::name('merchant')
            ->join('x_sort','x_sort.id = x_merchant.sort_id')
            ->join('x_floor','x_floor.id = x_merchant.floor_id')
            ->field('x_merchant.*,x_sort.name as sort,x_floor.name as floor')
            ->where('x_merchant.id',$id)
            ->find();
        // 该店铺的活动内容信息
        $activity = Db::name('activity')->where('merchant_id',$id)->select();
        foreach ($activity as $k=>$v){
            $activity[$k]['starttime'] = date('Y-m-d H:i:s',$v['starttime']);
            $activity[$k]['endtime'] = date('Y-m-d H:i:s',$v['endtime']);
        }
        return json_encode(['res'=>$res,'star'=>$star,'activity'=>$activity]);
    }
    // 收藏
    public function keep(){
        $params = $this->request->post();
        $params['createtime'] = time();
        $people = model('People')->people($params['openid']);
        array_shift($params);
        $params['people_id'] = $people['id'];
        $count = Db::name('keep')->where(array('people_id'=>$people['id'],'merchant_id'=>$params['merchant_id']))->find();
        if($count){
            $res = Db::name('keep')->where('id',$count['id'])->delete();
        }else{
            $res = Db::name('keep')->insert($params);
        }
        return $res?200:400;
    }

}
